<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--区域数据-->
            <el-col :span="4" :xs="24">
                <div class="box-card">
                    <div class="head-container">
                        <el-input v-model="filterText" placeholder="请输入区域名称" clearable size="small"
                            prefix-icon="el-icon-search" style="margin-bottom: 20px" />
                    </div>
                    <div class="head-container">
                        <el-tree :data="regionList" :props="defaultProps" :expand-on-click-node="false"
                            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all
                            highlight-current @node-click="handleNodeClick">
                            <div class="custom-tree-node" slot-scope="{ node, data }">
                                <div>{{ node.label }}</div>
                                <div>
                                    <i class="el-icon-edit" @click.stop="() => setEditRegion(data)"></i>
                                    <i class="el-icon-delete" style="margin-left: 10px;"
                                        @click.stop="() => setDelRegion(data)"></i>
                                </div>
                            </div>
                        </el-tree>
                    </div>
                </div>
            </el-col>
            <!--房间数据-->
            <el-col :span="20" :xs="24">
                <el-form :model="queryParamsRoom" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                    label-width="68px">
                    <el-form-item label="房间名称" prop="userName">
                        <el-input v-model="queryParamsRoom.name" placeholder="请输入房间名称" clearable style="width: 240px"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddRegion"
                            v-hasPermi="['system:user:add']">新增区域</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddRoom"
                            v-hasPermi="['system:user:add']">新增房间</el-button>
                    </el-col>
                    <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"
                        :columns="columns"></right-toolbar> -->
                </el-row>

                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" height="650"
                    style="width: 100%">
                    <el-table-column prop="regionName" label="位置">
                    </el-table-column>
                    <el-table-column prop="name" label="房间">
                    </el-table-column>
                    <el-table-column prop="maxNumber" label="最大人数">
                    </el-table-column>
                    <el-table-column prop="roomType" label="房间类型">
                    </el-table-column>
                    <el-table-column label="操作" width="150">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" icon="el-icon-edit"
                                @click="setEdit(scope.row)">编辑</el-button>
                            <el-button type="text" size="small" icon="el-icon-delete"
                                @click="setDel(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-col>
        </el-row>

        <!-- 新增区域 -->
        <el-drawer :title="regionTitle" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
            <el-form :model="formInline" class="demo-form-inline">
                <el-form-item label="位置名称">
                    <el-input v-model="formInline.locationName" placeholder="位置名称"></el-input>
                </el-form-item>
                <el-form-item class="btn">
                    <el-button type="primary" @click="onSubmit">确认</el-button>
                    <el-button @click="resetForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>



        <!-- 新增房间 -->
        <el-drawer :title="roomTitle" :visible.sync="drawerRoom" :direction="direction" :before-close="handleClose">
            <el-form :model="formInlineRoom" class="demo-form-inline" label-position="top">
                <el-form-item label="名称">
                    <el-input v-model="formInlineRoom.name" placeholder="名称"></el-input>
                </el-form-item>
                <el-form-item label="人数">
                    <el-input v-model="formInlineRoom.maxNumber" placeholder="人数"></el-input>
                </el-form-item>
                <el-form-item label="房间类型">
                    <el-select v-model="formInlineRoom.roomType" placeholder="请选择房间类型" style="width: 100%;">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="位置">
                    <el-select v-model="formInlineRoom.regionId" placeholder="请选择位置" style="width: 100%;">
                        <el-option v-for="item in regionList" :key="item.value" :label="item.locationName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备">
                    <el-select v-model="formInlineRoom.deviceId" placeholder="请选择位置" style="width: 100%;">
                        <el-option v-for="item in deviceList" :key="item.value" :label="item.deviceName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="审批组">
                    <el-select v-model="formInlineRoom.auditName" placeholder="请选择房间类型" style="width: 100%;">
                        <el-option v-for="item in auditNameList" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="formInlineRoom.remarks" placeholder="备注"></el-input>
                </el-form-item>
                <el-form-item label="背景">
                    <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :headers="header"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="formInlineRoom.background" :src="formInlineRoom.background" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item class="btn">
                    <el-button type="primary" @click="onSubmitRoom">确认</el-button>
                    <el-button @click="resetForm">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<script>
import { listNoPage, addRegion, addRoom, listRoom, editRoom, editRegion, delRegion, delRoom } from "@/api/region/index";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { list } from '@/api/information/index';

export default {
    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: { Treeselect },
    data() {
        return {
            filterText: '',
            url: process.env.VUE_APP_BASE_API + '/iot/upload',
            header: {
                Authorization: 'Bearer ' + getToken(),
                clientid: process.env.VUE_APP_CLIENT_ID
            },
            drawerRoom: false,
            roomTitle: "新增房间",
            direction: 'rtl',
            drawer: false,
            regionTitle: "添加区域",
            formInline: {
                id: "",
                locationName: ""
            },
            formInlineRoom: {
                id: "",
                name: "",
                roomType: "",
                maxNumber: "",
                regionId: "",
                remarks: "",
                background: "",
                auditName: "",
                deviceId: ''
            },
            auditNameList: [{
                value: '不审批',
                label: '不审批'
            }],
            options: [{
                value: '会议室',
                label: '会议室'
            }, {
                value: '非会议室',
                label: '非会议室'
            }],
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: null,
            // 弹出层标题
            title: "",
            // 部门树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            // 部门名称
            deptName: undefined,
            // 默认密码
            initPassword: undefined,
            regionList: [],
            deviceList: [],
            // 日期范围
            dateRange: [],
            // 岗位选项
            postOptions: [],
            // 角色选项
            roleOptions: [],
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "locationName"
            },
            queryParamsRoom: {
                pageNum: 1,
                pageSize: 10,
                regionId: "",
                name: ""
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            // 列信息
            columns: [
                { key: 0, label: `用户编号`, visible: true },
                { key: 1, label: `用户名称`, visible: true },
                { key: 2, label: `用户昵称`, visible: true },
                { key: 3, label: `部门`, visible: true },
                { key: 4, label: `手机号码`, visible: true },
                { key: 5, label: `状态`, visible: true },
                { key: 6, label: `创建时间`, visible: true }
            ],
            // 表单校验
            rules: {
                userName: [
                    { required: true, message: "用户名称不能为空", trigger: "blur" },
                    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
                ],
                nickName: [
                    { required: true, message: "用户昵称不能为空", trigger: "blur" }
                ],
                password: [
                    { required: true, message: "用户密码不能为空", trigger: "blur" },
                    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
                    { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
                ],
                email: [
                    {
                        type: "email",
                        message: "请输入正确的邮箱地址",
                        trigger: ["blur", "change"]
                    }
                ],
                phonenumber: [
                    {
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: "请输入正确的手机号码",
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    watch: {
        // 根据名称筛选部门树
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        this.getList();
        this.getDeptTree();
        this.getListDevice();
    },
    methods: {
        async getListDevice() {
            this.loading = true;
            const res = await list({
                pageSize:9999,
                pageNum: 1
            });
            this.deviceList = res.rows;
        },
        setEditRegion(data) {
            this.drawer = true
            this.formInline = data
        },
        setDelRegion(data) {
            this.$confirm('此操作将永久删除该房间,' + data.locationName + '是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delRegion(data.id).then(response => {
                    this.getDeptTree();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }
                );
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        setDel(row) {
            this.$confirm('此操作将永久删除该区域,' + row.name + '是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delRegion(row.id).then(response => {
                    this.getList()
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }
                );
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        setEdit(row) {
            this.formInlineRoom = Object.assign({}, row)
            this.drawerRoom = true
            this.roomTitle = "修改房间"
        },
        editRoomConfirm() {
            editRoom(this.formInlineRoom).then(response => {
                this.$message({
                    message: '修改成功',
                    type: 'success'
                });
                this.getListRoom()
                this.resetForm()
            }
            );
        },
        onSubmitRoom() {
            if (this.formInlineRoom.id) {
                this.editRoomConfirm()
                return;
            }
            addRoom(this.formInlineRoom).then(response => {
                this.$message({
                    message: '添加成功',
                    type: 'success'
                });
                this.drawerRoom = false
                this.formInlineRoom = {
                    id: "",
                    name: "",
                    roomType: "",
                    maxNumber: "",
                    regionId: "",
                    remarks: "",
                    background: "",
                    auditName: ""
                }
            }
            );
        },
        handleAvatarSuccess(res, file) {
            console.log(res, file)
            this.formInlineRoom.background = res.data.url
        },
        beforeAvatarUpload(file) {
        },
        // 新增区域
        handleAddRegion() {
            this.drawer = true
        },
        // 新增房间
        handleAddRoom() {
            this.drawerRoom = true
        },
        /** 查询区域列表 */
        getList() {
            listNoPage(this.queryParams).then(response => {
                this.regionList = response.data;
                if (this.regionList.length > 0) {
                    this.handleNodeClick(this.regionList[0])
                }
            }
            );
        },
        /** 查询房间 */
        getListRoom() {
            this.loading = true
            listRoom(this.queryParamsRoom).then(response => {
                this.userList = response.rows;
                this.total = response.total
                this.loading = false
            }
            );
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        },
        onSubmit() {
            if (this.formInline.id) {
                editRegion(this.formInline).then(response => {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.resetForm()
                    this.getList()
                }
                );
            } else {
                addRegion(this.formInline).then(response => {
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });
                    this.resetForm()
                    this.getList()
                }
                );
            }
        },
        resetForm() {
            this.drawer = false
            this.drawerRoom = false
            this.formInline = {
                id: '',
                locationName: ''
            }
            this.formInlineRoom = {
                id: "",
                name: "",
                roomType: "",
                maxNumber: "",
                regionId: "",
                remarks: "",
                background: "",
                auditName: ""
            }
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
        },
        // 筛选节点
        filterNode(value, data) {
            console.log(value, data)
            if (!value) return true;
            return data.locationName.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParamsRoom.regionId = data.id;
            this.getListRoom();
        },
        // 用户状态修改
        handleStatusChange(row) {
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                userId: undefined,
                deptId: undefined,
                userName: undefined,
                nickName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: "0",
                remark: undefined,
                postIds: [],
                roleIds: []
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getListRoom();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.queryParams.deptId = undefined;
            this.$refs.tree.setCurrentKey(null);
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleResetPwd":
                    this.handleResetPwd(row);
                    break;
                case "handleAuthRole":
                    this.handleAuthRole(row);
                    break;
                default:
                    break;
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId;
            this.$router.push("/system/user-auth/role/" + userId);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.userId != undefined) {
                        updateUser(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addUser(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const userIds = row.userId || this.ids;
            this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
                return delUser(userIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/user/export', {
                ...this.queryParams
            }, `user_${new Date().getTime()}.xlsx`)
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "用户导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('system/user/importTemplate', {
            }, `user_template_${new Date().getTime()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        }
    }
};
</script>

<style scoped>
.demo-form-inline {
    padding: 20px;
}

.btn {
    width: 100%;
    text-align: right;
}

.box-card {
    height: 100vh;
    border-right: 1px solid #eee;
    padding: 10px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    padding-right: 8px;
}

.el-tree-node__expand-icon.is-leaf {
    display: none;
}
</style>